//
//  ReceiverTextField.m
//  TengyunStation
//
//  Created by Johnny on 15/8/24.
//  Copyright (c) 2015年 xingrong. All rights reserved.
//

#import "ReceiverTextField.h"
#import "ReceiverCell.h"
#import "DSToast.h"
#import "TSHeader.h"
#define ReceiverCellHeight      30

@implementation ReceiverTextField

- (void)awakeFromNib {
    if (!_telephoneTableView) {
        UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(self.frame.origin.x, self.frame.origin.y + self.frame.size.height, self.frame.size.width, 44)];
        tableView.dataSource = self;
        tableView.delegate = self;
        tableView.layer.borderColor = LineColor.CGColor;
        tableView.layer.borderWidth = 1;
        _telephoneTableView = tableView;
    }
    self.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
    self.delegate = self;
    _isShowTableView = NO;
    [self addTarget:self action:@selector(textFieldEditingChanged:) forControlEvents:UIControlEventEditingChanged];
}

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self awakeFromNib];
    }
    return self;
}

- (void)reloadTableView {
    if (!_isShowTableView) {
        [self showTableView];
    }
    if (_telephoneList.count < 4) {
        _telephoneTableView.frame = CGRectMake(_telephoneTableView.frame.origin.x, _telephoneTableView.frame.origin.y, _telephoneTableView.frame.size.width, ReceiverCellHeight * _telephoneList.count);
    } else {
        _telephoneTableView.frame = CGRectMake(_telephoneTableView.frame.origin.x, _telephoneTableView.frame.origin.y, _telephoneTableView.frame.size.width, ReceiverCellHeight * 4);
    }
    [_telephoneTableView reloadData];
}

- (void)showTableView {
    [self.superview addSubview:_telephoneTableView];
    _isShowTableView = YES;
}

- (void)removeTableView {
    [_telephoneTableView removeFromSuperview];
    _isShowTableView = NO;
}

#pragma mark UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    NSString *sqlString = [NSString stringWithFormat:@"WHERE telephone like '%%%@%%' ORDER BY saveday DESC",textField.text];
    _telephoneList = [ReceiverDBModel findByCriteria:sqlString];
    [self reloadTableView];
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:TelephoneLimit] invertedSet];
    NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
    if (![string isEqualToString:filtered]) {
        return NO;
    }
    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    if (_isShowTableView) {
        [self removeTableView];
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField.text.length <= 11) {
        [DSToast showText:@"手机号输入不正确" InView:self.superview ShowType:DSToastShowTypeCenter];
        return NO;
    }
    return YES;
}

#pragma mark UITextFieldAction
- (void)textFieldEditingChanged:(UITextField *)textField {
    if (textField.text.length < 11) {
        NSString *sqlString = [NSString stringWithFormat:@"WHERE telephone like '%%%@%%' ORDER BY saveday DESC",textField.text];
        _telephoneList = [ReceiverDBModel findByCriteria:sqlString];
        [self reloadTableView];
    } else {
        textField.text = [textField.text substringToIndex:11];
        ReceiverDBModel *receiver = [ReceiverDBModel findFirstByCriteria:[NSString stringWithFormat:@"WHERE telephone = '%@'",self.text]];
        if (receiver == nil) {
            self.receiverModel = [[ReceiverDBModel alloc] init];
            self.receiverModel.telephone = textField.text;
        } else {
            self.receiverModel = receiver;
        }
        if ([_receiverDelegate respondsToSelector:@selector(didFinishEditingReceiverTextField)]) {
            [_receiverDelegate didFinishEditingReceiverTextField];
        }
    }
}

#pragma mark UITableViewDataSource,UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _telephoneList.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return ReceiverCellHeight;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIndentifier = @"ReceiverCell";
    ReceiverCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIndentifier];
    if (!cell) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"ReceiverCell" owner:self options:nil] lastObject];
    }
    ReceiverDBModel *receiver = [_telephoneList objectAtIndex:indexPath.row];
    [cell reloadReceiverCellWithReceiverModel:receiver SameText:self.text];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    ReceiverDBModel *receiver = [_telephoneList objectAtIndex:indexPath.row];
    self.text = receiver.telephone;
    self.receiverModel = receiver;
    if ([_receiverDelegate respondsToSelector:@selector(didFinishEditingReceiverTextField)]) {
        [_receiverDelegate didFinishEditingReceiverTextField];
    }
}

- (void)dealloc {
    _telephoneList = nil;
    _telephoneTableView = nil;
    _receiverDelegate = nil;
    _receiverModel = nil;
}

@end
